package com.example.s05_shop.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.s05_shop.pojo.*;
import com.example.s05_shop.service.ICategoryService;
import com.example.s05_shop.service.IOrdersService;
import com.example.s05_shop.service.IProductService;
import com.example.s05_shop.service.IUserService;
import org.apache.tomcat.util.http.parser.HttpParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

@Controller
public class UserController {


    @Autowired
    private IProductService productService;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IOrdersService ordersService;

    @RequestMapping("/")
    public String index(Model m) {
        System.out.println("用户首页");

        // 查询分类信息
        List<Category> categories = categoryService.list();
        m.addAttribute("categories", categories);
        Map<Integer, List<Product>> productsMap = new HashMap<>();
        // 查询分类下5件商品
        for (Category c : categories) {
            QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("c_id", c.getId());
            queryWrapper.last("limit 5");
            List<Product> products = productService.list(queryWrapper);
            productsMap.put(c.getId(), products);
        }
        m.addAttribute("productsMap", productsMap);

        return "index";
    }

    @RequestMapping("/register")
    public String register() {
        return "register";
    }

    @RequestMapping("/registerchk")
    public String registerchk(User user) {

        boolean result = userService.save(user);
        if(result) {
            // 注册成功跳转登录页
            return "redirect:/login";
        }
        else{
            // 注册失败重新跳回注册页
            return "rediect:/register";
        }
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/loginchk")
    public String loginchk(String username,String password,HttpSession session) {

        System.out.println("loginchk");


        QueryWrapper<User> qw = new QueryWrapper<>();
        // where username = 'zhangsan' and password = '123456';
        qw.eq("username",username).eq("password",password);
        List<User> list = userService.list(qw);
        if(list.size()>0)
        {
            // 将登录信息放到session
            session.setAttribute("user",list.get(0));
            System.out.println("登录成功,跳转首页");
            return "redirect:/";
        }
        else {
            System.out.println("登录失败，跳转登录页");
            return "redirect:/login";
        }
    }


    @RequestMapping("/logout")
    public String logout(HttpSession session)
    {
        session.removeAttribute("user");
//        session.invalidate();
        return "redirect:/";
    }


    @RequestMapping("/category")
    public String category(int cid,
                           @RequestParam(value = "page", required = true, defaultValue = "1") int page,
                           @RequestParam(value = "size", required = true, defaultValue = "4") int size,
                           Model m) {
        System.out.println("catgory list()");

        // 页面信息
        IPage<Product> pageBean = new Page<>();
        pageBean.setCurrent(page);// 第几页
        pageBean.setSize(size);// 每页数量

        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("c_id", cid);
        // 查询
        IPage<Product> pageInfo = productService.page(pageBean, queryWrapper);

        // 放入model
//        m.addAttribute("list",list);
        m.addAttribute("pageBean", pageBean);

        // 查询商品分类信息
        List<Category> categories = categoryService.list();
        m.addAttribute("categories", categories);


        // 返回视图
        return "category";
    }

    @RequestMapping("product")
    public String product(int id, Model m) {
        // 查询商品分类信息
        List<Category> categories = categoryService.list();
        m.addAttribute("categories", categories);

        Product p = productService.getById(id);
        m.addAttribute("p", p);
        return "product";
    }


    /**
     * 添加到购物车
     *
     * @param id            商品编号
     * @param count         商品数量
     * @return
     */
    @RequestMapping("addcart")
    public String addCart(int id, int count, HttpSession session) {

        System.out.println("添加购物车"+id+","+count);

        // 1 查询商品信息
        Product p = productService.getById(id);
        // 2. 创建购物车项
        CartItem item = new CartItem(p,count,p.getPrice().doubleValue()*count);
        // 3. 放入购物车
        // 判断会话中是否已有购物车
        Cart c = (Cart)session.getAttribute("cart");
        if(c==null) {
            c = new Cart();
        }
        // 判断购物车中是否已有该商品
        if(c.getItems().keySet().contains(id))
        {
            // 原本购物车里的数量
            int oldCount = c.getItems().get(id).getCount(); // 3
            // 加到新放入的数量上
            item.setCount(item.getCount()+oldCount); // 5+3  = 8
        }
        c.getItems().put(id,item); // 8
        // 4. 放入用户的会话中
        session.setAttribute("cart",c);
        System.out.println("数量:"+c.getItems().size());


//        c.getItems().keySet()
//        c.getItems().values()

        return "redirect:/cart";
    }

    @RequestMapping("cart")
    public String delCart()
    {
        return "cart";
    }


    @RequestMapping("delcart")
    public String delCart(int id,HttpSession session)
    {
        // 1.
        Cart c = (Cart)session.getAttribute("cart");
        c.getItems().remove(id);

        return "redirect:/cart";
    }

    @RequestMapping("modifycart")
    @ResponseBody
    public String modifyCart(int pid,int count,HttpSession session)
    {
        // 1.
        Cart c = (Cart)session.getAttribute("cart");
        CartItem item = c.getItems().get(pid);
        item.setCount(count);
        item.setTotalPrice(item.getP().getPrice().doubleValue()*count);
        session.setAttribute("cart",c);

        //
        return "ok";
    }



    @RequestMapping("addorder")
    public String addorder(int[] pid,HttpSession session)
    {
        System.out.println(Arrays.toString(pid));

        User u = (User)session.getAttribute("user");
        if(u==null)
        {
            return "redirect:/login";
        }
        Cart c = (Cart)session.getAttribute("cart");

        // 创建订单 和订单项
        Orders o = new Orders();
        // 用户编号
        o.setUserId(u.getId());
        o.setName(u.getName());
        o.setAddress(u.getAddress());
        o.setTel(u.getTel());
        o.setStatus("待支付");

        // 订单项列表
        List<OrdersItem> items = new ArrayList<>();



        // 创建订单项
        for(int p:pid)
        {
            // 订单项
            OrdersItem oi = new OrdersItem();

            // 购物车项
            CartItem ci =  c.getItems().get(p);

            // 产品编号
            oi.setProductId(ci.getP().getId());
            // 产品价格
            oi.setPrice(ci.getP().getPrice());
            // 购买数量
            oi.setCount(ci.getCount());
            // 总价(价格*数量)
            oi.setTotalPrice(new BigDecimal(ci.getTotalPrice()));

            // 放入商品信息
            oi.setProduct(ci.getP());

            // 添加订单项列表
            items.add(oi);

            // 更新订单总价
            o.setTotalPrice(o.getTotalPrice().add(oi.getTotalPrice()));

        }

        // 保存到用户会话中
        session.setAttribute("orders",o);
        session.setAttribute("ordersItems",items);


        return "confirmorder";
    }


    @RequestMapping("/submitorder")
    public String submitOrder(String name,String tel,String address,HttpSession session)
    {
        // 把订单信息 订单保存到数据库中
        Orders o = (Orders) session.getAttribute("orders");
        List<OrdersItem> items = (List<OrdersItem>) session.getAttribute("ordersItems");

        // 保存订单及订单相亲
        boolean result = ordersService.save(o,items);

        // 跳转到支付页面

        // 跳转到订单列表页
        return "redirect:/orderlist";
    }

    @RequestMapping("/orderlist")
    public String submitOrder(HttpSession session,Model m)
    {
        // 提数据
        User u = (User) session.getAttribute("user");

        if(u==null)
        {
            return "redirect:/login";
        }

        // 查询订单列表
        List<Orders> orders = ordersService.listByUserId(u.getId());
        System.out.println(orders);

        // 放入模型
        m.addAttribute("orders",orders);

        return "orderlist";
    }
}

